"use strict";

/**
 * @auther wtfssd
 * Created by wtfssd on 2017/12/25
 */
import * as React from 'react'
import {autoSize, commonProps, commonStyles} from "../../assets/styles/common";
import Colors from "../../assets/styles/Colors";
import NavBackButton from "../../component/BackButton";
import MyText from "../../component/MyText";
import Avatar from "../../component/Avatar";
import {messageStyle} from "../../assets/styles/message";
import {messageList} from "../../assets/data";
import ContactUser from "../../component/ContactUser";
import {NewMessagePage} from "../../interface/router";
import Request from "../../utils/Request";
import {kAuthorization} from "../../constant";
import MyImage from "../../component/MyImage";
import constant from "../../utils/constant";

const {View, TextInput, TouchableOpacity, FlatList, DeviceEventEmitter} = require('react-native');
const NavigationBar = require('react-native-navbar').default;
const {Actions} = require("react-native-router-flux");
const {connect} = require('react-redux');
const {GiftedChat} = require('react-native-gifted-chat');


class Page extends React.Component<NewMessagePage, any> {


    input: any;
    searchUrl: string;
    state = {
        receiver: null,
        inputValue: null,
        messages: [],

    };


    constructor(props: NewMessagePage, context: any) {
        super(props, context);
        this.searchUrl = Request.getApi().searchUser;
    }

    componentDidMount(): void {
        this.setState({
            messages: [
                {
                    _id: 1,
                    text: 'Hello developer',
                    createdAt: new Date(),
                    user: {
                        _id: 2,
                        name: 'React Native',
                        avatar: 'https://facebook.github.io/react/img/logo_og.png',
                    },
                },
            ],
        });
    }

    //发送按钮点击
    onSend(messages = []) {
        DeviceEventEmitter.emit(constant.noticeKeyOfSendMessage, {
            receiver: this.state.receiver.account,
            sender: this.props.auth.userInfo.account,
            receiverId: this.state.receiver.id,
            senderId: this.props.auth.userInfo.id,
            message: messages[0],
            nickname: this.props.auth.userInfo.nickName,
            avatar: this.props.auth.userInfo.avatar || '',
        });
    }

    //输入框更改
    onChangeText = (text: string) => {
        this.setState({receiver: null});
        this.props.dispatch({
            type: 'chat/searchUser',
            payload: {
                pi: 1,
                ps: 40,
                nickName: text,
            }
        });
    };

    //收信人点击
    onReceiverItemPress = (item: userItem) => {
        this.setState({receiver: item});
        this.fetchMessageList(item);
    };

    //获取消息列表
    fetchMessageList = (receiver: userItem) => {

        this.props.dispatch({
            type: 'chat/fetchMessageList',
            payload: {
                receiver: receiver.account,
                pi: 1,
                ps: 20
            }
        });

        this.props.dispatch({
            type: 'message/readMessageFromUser',
            payload: {
                receiver: receiver.account,
            }
        })
    };

    onLoadMore = (loadmore) => {
        if (!this.props.chat.messageList.last) {
            this.props.dispatch({
                type: 'chat/fetchMessageList',
                payload: {
                    receiver: this.state.receiver.account,
                    pi: this.props.chat.messageList.number + 2,
                    ps: 20,
                    loadmore: true
                }
            });
        }
    };


    renderLoading = () => {
        return (
            <View style={[commonStyles.flex1, commonStyles.centerVH]}>
                <MyText>初始化中...</MyText>
            </View>
        )
    };


    /**
     * 提示
     * @return {any}
     */
    renderTipView = () => {
        if (this.state.receiver) return null;
        let tip = '暂无结果';
        if (this.props.chat.searchUsers && this.props.chat.searchUsers.content.length > 0) {
            tip = `匹配到${this.props.chat.searchUsers.content.length}名会员`
        }
        return (
            <View style={{backgroundColor: Colors.Background, paddingLeft: 60, paddingVertical: 10}}>
                <MyText color={Colors.Black} fontSize={15} fontWeight={'500'}>{tip}</MyText>
            </View>
        )
    };

    //收信人详情
    renderReceiverItem = (props) => {
        const item: userItem = props.item;
        let info = '';
        if (item.duty) {
            info += item.duty + 'at ';
        }
        if (item.company) {
            info += item.company.name;
        }
        let avatar = Request.checkImageUrl(item.avatar) + '';
        if (avatar && avatar.toLocaleLowerCase().indexOf('default-avatar.png')!==-1) {
            avatar = '';
        }
        return (
            <TouchableOpacity onPress={this.onReceiverItemPress.bind(this, item)}>
                <View style={[commonStyles.flexRow, messageStyle.messageContainer]}>
                    <View style={[commonStyles.centerVH]}>
                        <Avatar source={{uri: item.avatar}} size={autoSize(65)}
                                 placeholder={require('../../assets/image/default-avatar.png')}/>
                    </View>
                    <View style={[commonStyles.flexColumn, commonStyles.flex1, messageStyle.infoContainer]}>
                        <MyText style={messageStyle.text} fontSize={15}
                                color={Colors.Title}>{item.nickName}</MyText>
                        <MyText style={messageStyle.text} fontSize={15} color={Colors.Title}
                                numberOfLines={1}>{info}</MyText>
                        {/*<MyText style={messageStyle.text} fontSize={12} color={Colors.SubTitle}>{item.time}</MyText>*/}
                    </View>
                </View>
            </TouchableOpacity>
        )
    };
    //收信人列表
    renderReceiverList = () => {
        if (this.state.receiver) return null;
        if (!this.props.chat.searchUsers || this.props.chat.searchUsers.content.length <= 0) return null;
        return (
            <FlatList data={this.props.chat.searchUsers.content}
                      style={{backgroundColor: Colors.White}}
                      keyboardDismissMode={'on-drag'}
                      keyExtractor={(_, index) => index}
                      extraData={this.props.chat.searchUsers}
                      renderItem={this.renderReceiverItem}/>
        )
    };

    //通讯UI
    renderChatView = () => {
        if (!this.state.receiver) return null;
        return (
            <View style={[commonStyles.flex1, {backgroundColor: Colors.White}]}>
                <ContactUser user={this.state.receiver}/>
                <GiftedChat
                    messages={this.props.chat.messageList ? this.props.chat.messageList.content : []}
                    onSend={(messages) => this.onSend(messages)}
                    renderLoading={this.renderLoading}
                    onLoadEarlier={this.onLoadMore}
                    loadEarlier={true}
                    isLoadingEarlier={this.props.chat.loading}
                    user={{
                        _id: this.props.auth.userInfo.account,
                    }}
                />
            </View>

        )
    };

    render() {
        return (
            <View style={[commonStyles.container]}>
                <NavigationBar {...commonProps.navBar}
                               leftButton={<NavBackButton
                                   icon={{name: 'icon-cha1', color: Colors.White, size: autoSize(24)}}/>}
                               title={{title: this.props.title, tintColor: '#fff'}}
                />
                <View
                    style={[commonStyles.flexRow, {alignItems: 'center', padding: 10, backgroundColor: Colors.White}]}>
                    <MyText color={Colors.SubTitle} fontSize={15}>收件人:</MyText>
                    <TextInput placeholder='输入联系人'
                               autoFocus
                               defaultValue={this.state.receiver ? this.state.receiver.nickName : ''}
                               ref={ref => this.input = ref}
                               onChangeText={this.onChangeText}
                               style={{fontSize: 15, display: 'flex', flex: 1}}/>
                </View>
                {this.renderTipView()}
                {this.renderReceiverList()}
                {this.renderChatView()}
            </View>

        );
    }
}


export default connect(
    ({auth, message, chat}) => ({auth, message, chat})
)(Page);